package com.yy.service.impl;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.yy.config.ApiConfig;
import com.yy.dto.mother.*;
import com.yy.service.MotherChildrenService;
import com.yy.utils.OrderProcessor;
import com.yy.utils.SecretUtil;
import com.yy.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 姚欣宏
 * @since 2023-07-10
 */
@Slf4j
@Service
public class MotherChildrenServiceImpl implements MotherChildrenService {
    @Autowired
    private ApiConfig apiConfig;

    private Map<String, String> getHeaders() {
        return apiConfig.getHeaders();
    }

    private String getUrlByName(String name) {
        return apiConfig.getEndpoints().stream()
                .filter(endpoint -> endpoint.getName().equals(name))
                .findFirst()
                .map(ApiConfig.Endpoint::getUrl)
                .orElseThrow(() -> new RuntimeException("No endpoint found with name: " + name));
    }

    @Override
    public AuthDataDTO getAuthCode(String phoneNum) {
        // 请求地址
        String url = getUrlByName("authcode");
        // 设置请求头
        Map<String, String> headers = getHeaders();
        // 请求参数
        Map<String, Object> params = new HashMap<>();
        params.put("organCode", "HXD2");
        params.put("appCode", "HXFYAPP");
        params.put("channelCode", "PATIENT_WECHAT_APPLET");
        params.put("phoneNum", phoneNum);
        params.put("busiCode", "hyt_account");
        params.put("tempCode", "normal");
        params.put("clientId", "ooo9znbykh");
        params.put("needCheck", false);
        // 发起请求
        HttpResponse response = HttpRequest.post(url)
                .addHeaders(headers)
                .body(JSONUtil.toJsonStr(params))
                .execute();
        // 从请求中获取的JSON字符串
        String jsonStr = response.body();
        // 使用Hutool的JSONUtil将字符串转换为对象
        CommonResponseDTO<AuthDataDTO> commonResponse = JSONUtil.toBean(jsonStr, new TypeReference<CommonResponseDTO<AuthDataDTO>>() {
        }, false);
        // 获取AuthDataDTO数据
        if (Objects.isNull(commonResponse.getData())) {
            throw new RuntimeException(commonResponse.getMsg());
        }
        return commonResponse.getData();
    }

    @Override
    public LoginResponseDataDTO login(WeChatLoginVO weChatLoginVO) {
        // 请求地址
        String url = getUrlByName("login");
        // 设置请求头
        Map<String, String> headers = getHeaders();

        // 将WeChatLoginVO转换为JSON字符串
        String jsonRequestBody = JSONUtil.toJsonStr(weChatLoginVO);

        // 发起请求
        HttpResponse response = HttpRequest.post(url)
                .addHeaders(headers)
                .body(jsonRequestBody)
                .execute();

        // 从请求中获取的JSON字符串
        String jsonStr = response.body();
        log.info("华西附二院登陆：" + jsonStr);
        // 使用Hutool的JSONUtil将字符串转换为对象
        CommonResponseDTO<LoginResponseDataDTO> commonResponse = JSONUtil.toBean(jsonStr, new TypeReference<CommonResponseDTO<LoginResponseDataDTO>>() {
        }, false);

        if (Objects.isNull(commonResponse.getData())) {
            throw new RuntimeException(commonResponse.getMsg());
        }
        return commonResponse.getData();
    }

    @Override
    public List<UserOrganCardDetailDTO> getUserOrganCardList(CardRequestVO cardRequestVO) {
        // 请求地址
        String url = getUrlByName("cardList");
        // 设置请求头
        Map<String, String> headers = getHeaders();
        headers.put("accessToken", cardRequestVO.getToken());
        // 将WeChatLoginVO转换为JSON字符串
        String jsonRequestBody = JSONUtil.toJsonStr(cardRequestVO);
        // 发起请求
        HttpResponse response = HttpRequest.post(url)
                .addHeaders(headers)
                .body(jsonRequestBody)
                .execute();
        // 从请求中获取的JSON字符串
        String jsonStr = response.body();
        log.info("华西附二院就诊卡：" + jsonStr);
        // 使用Hutool的JSONUtil将字符串转换为对象
        CommonResponseDTO<List<UserOrganCardDetailDTO>> commonResponse = JSONUtil.toBean(jsonStr, new TypeReference<CommonResponseDTO<List<UserOrganCardDetailDTO>>>() {
        }, false);
        if (Objects.isNull(commonResponse.getData())) {
            throw new RuntimeException(commonResponse.getMsg());
        }
        return commonResponse.getData();
    }

    @Override
    public DepartmentInfoDTO selTree(TreeRequestVO treeRequestVO) {
        // 请求地址
        String url = getUrlByName("selTree");
        // 设置请求头
        Map<String, String> headers = getHeaders();
        headers.put("accessToken", treeRequestVO.getToken());
        // 将WeChatLoginVO转换为JSON字符串
        String jsonRequestBody = JSONUtil.toJsonStr(treeRequestVO);
        // 发起请求
        HttpResponse response = HttpRequest.post(url)
                .addHeaders(headers)
                .body(jsonRequestBody)
                .execute();
        // 从请求中获取的JSON字符串
        String jsonStr = response.body();
        log.info("selTree：" + jsonStr);
        // 使用Hutool的JSONUtil将字符串转换为对象
        CommonResponseDTO<DepartmentInfoDTO> commonResponse = JSONUtil.toBean(jsonStr, new TypeReference<CommonResponseDTO<DepartmentInfoDTO>>() {
        }, false);
        if (Objects.isNull(commonResponse.getData())) {
            throw new RuntimeException(commonResponse.getMsg());
        }
        return commonResponse.getData();
    }

    @Override
    public DetailedDataResponseDTO selDocListSelectionPage(TreeRequestVO treeRequestVO) {
        // 请求地址
        String url = getUrlByName("docList");
        // 设置请求头
        Map<String, String> headers = getHeaders();
        headers.put("accessToken", treeRequestVO.getToken());
        // 将WeChatLoginVO转换为JSON字符串
        String jsonRequestBody = JSONUtil.toJsonStr(treeRequestVO);
        // 发起请求
        HttpResponse response = HttpRequest.post(url)
                .addHeaders(headers)
                .body(jsonRequestBody)
                .execute();
        // 从请求中获取的JSON字符串
        String jsonStr = response.body();
        log.info("docList：" + jsonStr);
        // 使用Hutool的JSONUtil将字符串转换为对象
        CommonResponseDTO<DetailedDataResponseDTO> commonResponse = JSONUtil.toBean(jsonStr, new TypeReference<CommonResponseDTO<DetailedDataResponseDTO>>() {
        }, false);
        if (Objects.isNull(commonResponse.getData())) {
            throw new RuntimeException(commonResponse.getMsg());
        }
        return commonResponse.getData();
    }

    @Override
    public PageDoctorResponseDTO selDoctorListPaging(DoctorRequestVO doctorRequestVO) {
        // 请求地址
        String url = getUrlByName("doctorList");
        // 设置请求头
        Map<String, String> headers = getHeaders();
        headers.put("accessToken", doctorRequestVO.getToken());
        // 将WeChatLoginVO转换为JSON字符串
        String jsonRequestBody = JSONUtil.toJsonStr(doctorRequestVO);
        // 发起请求
        HttpResponse response = HttpRequest.post(url)
                .addHeaders(headers)
                .body(jsonRequestBody)
                .execute();
        // 从请求中获取的JSON字符串
        String jsonStr = response.body();
        log.info("doctorList：" + jsonStr);
        // 使用Hutool的JSONUtil将字符串转换为对象
        CommonResponseDTO<PageDoctorResponseDTO> commonResponse = JSONUtil.toBean(jsonStr, new TypeReference<CommonResponseDTO<PageDoctorResponseDTO>>() {
        }, false);
        // 获取AuthDataDTO数据
        return commonResponse.getData();
    }

    /**
     * @param doctorInfoRequestVO
     * @return
     */
    @Override
    public DataResponseDTO selDoctorSchedule(DoctorInfoRequestVO doctorInfoRequestVO) {
        // 请求地址
        String url = getUrlByName("doctorSchedule");
        // 设置请求头
        Map<String, String> headers = getHeaders();
        headers.put("accessToken", doctorInfoRequestVO.getToken());
        // 将WeChatLoginVO转换为JSON字符串
        String jsonRequestBody = JSONUtil.toJsonStr(doctorInfoRequestVO);
        // 发起请求
        HttpResponse response = HttpRequest.post(url)
                .addHeaders(headers)
                .body(jsonRequestBody)
                .execute();
        // 从请求中获取的JSON字符串
        String jsonStr = response.body();
        log.info("doctorSchedule：" + jsonStr);
        // 使用Hutool的JSONUtil将字符串转换为对象
        CommonResponseDTO<DataResponseDTO> commonResponse = JSONUtil.toBean(jsonStr, new TypeReference<CommonResponseDTO<DataResponseDTO>>() {
        }, false);
        if (Objects.isNull(commonResponse.getData())) {
            throw new RuntimeException(commonResponse.getMsg());
        }
        return commonResponse.getData();
    }

    /**
     * @param scheduleInfoRequestVO
     * @return
     */
    @Override
    public DoctorDetailDTO selSureOrderPage(ScheduleInfoRequestVO scheduleInfoRequestVO) {
        // 请求地址
        String url = getUrlByName("orderPage");
        // 设置请求头
        Map<String, String> headers = getHeaders();
        headers.put("accessToken", scheduleInfoRequestVO.getToken());
        // 将WeChatLoginVO转换为JSON字符串
        String jsonRequestBody = JSONUtil.toJsonStr(scheduleInfoRequestVO);
        // 发起请求
        HttpResponse response = HttpRequest.post(url)
                .addHeaders(headers)
                .body(jsonRequestBody)
                .execute();
        // 从请求中获取的JSON字符串
        String jsonStr = response.body();
        log.info("orderPage：" + jsonStr);
        // 使用Hutool的JSONUtil将字符串转换为对象
        CommonResponseDTO<DoctorDetailDTO> commonResponse = JSONUtil.toBean(jsonStr, new TypeReference<CommonResponseDTO<DoctorDetailDTO>>() {
        }, false);
        if (Objects.isNull(commonResponse.getData())) {
            throw new RuntimeException(commonResponse.getMsg());
        }
        return commonResponse.getData();
    }

    /**
     * @param appointmentRequestVO
     * @return
     */
    @Override
    public AppointmentResponseDTO orderCheck(AppointmentRequestVO appointmentRequestVO) {
        // 请求地址
        String url = getUrlByName("orderCheck");
        // 设置请求头
        Map<String, String> headers = getHeaders();
        headers.put("accessToken", appointmentRequestVO.getToken());
        // 将WeChatLoginVO转换为JSON字符串
        String jsonRequestBody = JSONUtil.toJsonStr(appointmentRequestVO);
        // 发起请求
        HttpResponse response = HttpRequest.post(url)
                .addHeaders(headers)
                .body(jsonRequestBody)
                .execute();
        // 从请求中获取的JSON字符串
        String jsonStr = response.body();
        log.info("orderCheck：" + jsonStr);
        // 使用Hutool的JSONUtil将字符串转换为对象
        CommonResponseDTO<AppointmentResponseDTO> commonResponse = JSONUtil.toBean(jsonStr, new TypeReference<CommonResponseDTO<AppointmentResponseDTO>>() {
        }, false);
        if (Objects.isNull(commonResponse.getData())) {
            throw new RuntimeException(commonResponse.getMsg());
        }
        return commonResponse.getData();
    }

    /**
     * @param imageRequestVO
     * @return
     */
    @Override
    public ImageCodeDTO getImageCode(ImageRequestVO imageRequestVO) {
        // 请求地址
        String url = getUrlByName("imageCode");
        // 设置请求头
        Map<String, String> headers = getHeaders();
        headers.put("accessToken", imageRequestVO.getToken());
        // 将WeChatLoginVO转换为JSON字符串
        String jsonRequestBody = JSONUtil.toJsonStr(imageRequestVO);
        // 发起请求
        HttpResponse response = HttpRequest.post(url)
                .addHeaders(headers)
                .body(jsonRequestBody)
                .execute();
        // 从请求中获取的JSON字符串
        String jsonStr = response.body();
        log.info("doctorSchedule：" + jsonStr);
        // 使用Hutool的JSONUtil将字符串转换为对象
        CommonResponseDTO<ImageCodeDTO> commonResponse = JSONUtil.toBean(jsonStr, new TypeReference<CommonResponseDTO<ImageCodeDTO>>() {
        }, false);
        if (Objects.isNull(commonResponse.getData())) {
            throw new RuntimeException(commonResponse.getMsg());
        }
        return commonResponse.getData();
    }

    /**
     * @param informationVO
     * @return
     */
    @Override
    public DetailResponseDTO sureOrder(InformationVO informationVO) {
        // 请求地址
        String url = getUrlByName("sureOrder");
        Map<String, Object> requestBodyMap = new HashMap<>();
        requestBodyMap.put("cardId", informationVO.getCardId());
        requestBodyMap.put("openId", "");
        requestBodyMap.put("scheduleId", informationVO.getScheduleId());
        requestBodyMap.put("organCode", informationVO.getOrganCode());
        requestBodyMap.put("sysTimeArrangeId", "");
        requestBodyMap.put("sureOrderVerify", "identifyingCode");
        requestBodyMap.put("sureOrderVerifyInfo", informationVO.getSureOrderVerifyInfo());
        requestBodyMap.put("sureOrderVerifyIndex", informationVO.getSureOrderVerifyIndex());
        requestBodyMap.put("verifyImageCodeType", "WECHAT");
        requestBodyMap.put("channelCode", "PATIENT_WECHAT_APPLET");
        String encryptParameter = OrderProcessor.encrypt(JSONUtil.toJsonStr(requestBodyMap));
        // 设置请求头
        log.info("加密参数" + encryptParameter);
        Map<String, String> headers = getHeaders();
        headers.put("encryptParameter", encryptParameter);
        headers.put("accessToken", informationVO.getToken());
        String jsonRequestBody = JSONUtil.toJsonStr(informationVO);
        log.info("sureOrder params:" + jsonRequestBody);
        // 发起请求
        HttpResponse response = HttpRequest.post(url)
                .addHeaders(headers)
                .body(jsonRequestBody)
                .execute();
        // 从请求中获取的JSON字符串
        String jsonStr = response.body();
        log.info("sureOrder：" + jsonStr);
        // 使用Hutool的JSONUtil将字符串转换为对象
        CommonResponseDTO<DetailResponseDTO> commonResponse = JSONUtil.toBean(jsonStr, new TypeReference<CommonResponseDTO<DetailResponseDTO>>() {
        }, false);
        if (Objects.isNull(commonResponse.getData())) {
            throw new RuntimeException(commonResponse.getMsg());
        }
        return commonResponse.getData();
    }

    /**
     * @param queryCriteriaVO
     * @return
     */
    @Override
    public PatientPageInfoDTO recordPage(QueryCriteriaVO queryCriteriaVO) {
        // 请求地址
        String url = getUrlByName("recordPage");
        // 设置请求头
        Map<String, String> headers = getHeaders();
        headers.put("accessToken", queryCriteriaVO.getToken());
        // 将WeChatLoginVO转换为JSON字符串
        String jsonRequestBody = JSONUtil.toJsonStr(queryCriteriaVO);
        // 发起请求
        HttpResponse response = HttpRequest.post(url)
                .addHeaders(headers)
                .body(jsonRequestBody)
                .execute();
        // 从请求中获取的JSON字符串
        String jsonStr = response.body();
        log.info("recordPage：" + jsonStr);
        // 使用Hutool的JSONUtil将字符串转换为对象
        CommonResponseDTO<PatientPageInfoDTO> commonResponse = JSONUtil.toBean(jsonStr, new TypeReference<CommonResponseDTO<PatientPageInfoDTO>>() {
        }, false);
        if (Objects.isNull(commonResponse.getData())) {
            throw new RuntimeException(commonResponse.getMsg());
        }
        return commonResponse.getData();
    }

    /**
     * @param cancelVO
     */
    @Override
    public void cancel(CancelVO cancelVO) {
        // 请求地址
        String url = getUrlByName("cancel");
        // 设置请求头
        Map<String, String> headers = getHeaders();
        headers.put("accessToken", cancelVO.getToken());
        // 将WeChatLoginVO转换为JSON字符串
        String jsonRequestBody = JSONUtil.toJsonStr(cancelVO);
        // 发起请求
        HttpResponse response = HttpRequest.post(url)
                .addHeaders(headers)
                .body(jsonRequestBody)
                .execute();
        // 从请求中获取的JSON字符串
        String jsonStr = response.body();
        log.info("cancel：" + jsonStr);
    }
}
